package com.woniuxy.three.pms.util;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.shiro.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * @ProjectName: Pms
 * @Package: com.woniuxy.three.pms.util
 * @ClassName: QiniuFileUploadUtil
 * @Author: 12092
 * @Description: 七牛云上传文件的工具包
 * @Date: 2019/6/27 12:41
 * @Version: 1.0
 */
public class QiniuFileUploadUtil {

    // 公钥
    public static final String QINIU_ACCESS_KEY = "v7TSSayjA11TMy9qDp-AqYtGK4gBsx5sQoG6hq8T";
    // 私钥
    public static final String QINIU_SECRET_KEY = "_B78rI69_V4oJsYcEuxZ4zMUSIz97aoksjT5K-Ds";
    // 命名空间
    public static final String QINIU_HEAD_IMG_BUCKET_NAME = "pms";
    // 域名  七牛云测试域名 30天后系统自动回收
    public static final String QINIU_HEAD_IMG_BUCKET_URL = "pt8kleudb.bkt.clouddn.com";


    public static String uploadImg(MultipartFile file) throws IOException {

        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(QINIU_ACCESS_KEY, QINIU_SECRET_KEY);
        String upToken = auth.uploadToken(QINIU_HEAD_IMG_BUCKET_NAME);
        Response response = uploadManager.put(file.getBytes(),null, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return putRet.key;
    }

    /***
     * 多文件上传
     * @param files
     * @return
     * @throws IOException
     */
    public static String uploadImages(MultipartFile[] files) throws IOException {
        StringBuffer path = new StringBuffer();
        for (MultipartFile file :files) {
            String uploadImg = QiniuFileUploadUtil.uploadImg(file);
            path.append(uploadImg+";") ;
        }
        //String sb = path.substring(0, path.length());
        return path.toString();
    }



    /*public static void main(String[] args) throws IOException {
        QiniuFileUploadUtil.uploadImg(new File("C:\\Users\\Administrator\\Desktop\\FncDEhwErCW8DdZOIAY0cz-sc1TV"),"FncDEhwErCW8DdZOIAY0cz-sc1TV");
    }*/

}
